<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\Controller;
use App\Http\Requests\Api\CategoriesRequest;
use App\Service\CategoryService;
use App\Transformers\CategoryTransformer;
use App\Transformers\GoodslistTransformer;
use Illuminate\Http\Request;
use App\Models\GoodCategory;
use phpDocumentor\Reflection\DocBlock;

class CategoriesController extends Controller
{
    //
    public function index(Request $request){
        if ($request->get('id')){
            $id = $request->get('id');
        }else{
            $id = 0;
        }
        $cat_ser = new CategoryService();
        $coll = collect($cat_ser->getCatetree($id));

        return $this->response->collection($coll,new CategoryTransformer());
    }



    public function store(CategoriesRequest $request, GoodCategory $category)
    {

        $category->cname = $request->cname;
        $category->parent_id = $request->parent_id;
        $category->save();
        return $this->response->array(['message'=>'添加成功'])->setStatusCode(201);

    }


    public function destory(GoodCategory $category){
        //police权限策略
        if ($category->goods()){
            return $this->response->array(['message'=>'该分类下有商品不能删除'])->setStatusCode(403);
        }
        $category->delete();
        return $this->response->noContent();
    }

    public function update(CategoriesRequest $request,GoodCategory $category){
        //权限

        //分类下的有商品判断
        if ($request->parent_id){
            if ($category->goods()){
                return $this->response->array(['message'=>'该分类下有商品不能更换所属分类'])->setStatusCode(403);
            }
        }

        $category->update($request->all());
        return $this->response->array(['message'=>' 更新成功'])->setStatusCode('200');
    }


}
